#-*- coding:utf-8 -*-
"""
公司层操作
"""
import json
import requests
from cgai_time.Time import TimeHandler

header = {
    'Content-Type':'application/json;charset=UTF-8',
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36',
}

ct = TimeHandler()

def get_basic_structure_department_id_map(token):
    """
    获取基本的架构部门及id 
    token: 获取到的token
    return:  {department_name : department_id}
    """
    url = "https://oapi.dingtalk.com/topapi/v2/department/listsub"  # 
    parms = {"access_token":token}
    res = requests.post(url,headers=header,params=parms)
    department_id_map = {}
    try:
        result = res.json()
        if result:
            _result = result['result']
            for i in _result:
                department_id_map[i['name']] = i['dept_id']
    except Exception as ERR:
        print(ERR)

    return department_id_map


def get_child_department_ids(dept_id,token):
    """
    获取部门的子部门id列表
    dept_id ： 部门id
    token: 获取的token
    return : []  只有部门id列表信息，没有部门信息
    """
    url = "https://oapi.dingtalk.com/topapi/v2/department/listsubid"  # 


    data = {'dept_id':dept_id }
    parms = {"access_token":token}
    res = requests.post(url,headers=header,params=parms,data=json.dumps(data))

    dept_id_list = []
    try:
        result = res.json()
        dept_id_list = result['result']['dept_id_list']
    except Exception as ERR:
        print(ERR)


    return dept_id_list



def get_user_ids_by_department_id(department_id,token):
    """
    根据部门id获取该部门的所有人员id
    department_id : 部门id
    token: 获取的token
    return :  {name:id,name:id,...}
    """
    url = "https://oapi.dingtalk.com/topapi/v2/user/list" 
    parms = {"access_token":token}
    cursor = 0
    has_more = False

    department_user_id_map = {}
    while True:
        if not has_more:
            data = {'dept_id':department_id ,'cursor':0,'size':20}
            res = requests.post(url,headers=header,params=parms,data=json.dumps(data))
            result = res.json()
            has_more = result['result']['has_more']
            user_list = result['result']['list']
            for i in user_list:
                name = i['name']
                userid = i['userid']
                department_user_id_map[name] = userid
            if has_more:
                next_cursor = result['result']['next_cursor']
                cursor += int(next_cursor)
            else:
                break
        else:
            break

    return department_user_id_map



def get_user_leave_status(userids,token,start_date,end_date):
    """
    获取各用户在指定日期范围内的请假记录
    userids: 用户id列表 []
    token: 获取的token
    start_date: 选择的起始日期
    end_date:   选择的结束日期
    """
    start_time = int(ct.strTime2TimeStamp(start_date + ' 00:00:00') * 1000)
    end_time = int(ct.strTime2TimeStamp(end_date + ' 23:59:59') * 1000)

    url = "https://oapi.dingtalk.com/topapi/attendance/getleavestatus"  # 

    userid = ','.join(userids)
    data = {
            'userid_list':userid,  # 这个是 逗号拼接的字符串
            'start_time':start_time,
            'end_time':end_time,
            'offset':0,
            'size':10
    }
    parms = {"access_token":token}
    res = requests.post(url,headers=header,params=parms,data=json.dumps(data))
    result = res.json()
    # print(result) 
    user_status = {}
    if result.get('success'):
        leave_status = result['result']['leave_status']
        for s in leave_status:
            stime = s['start_time']
            etime = s['end_time']
            userid = s['userid']
            s_t = ct.timeStamp2StrTime(stime/1000)
            e_t = ct.timeStamp2StrTime(etime/1000)
            # print(s_t,e_t)
            # 2022-12-01 00:00:00 2022-12-01 23:59:59
            # 2022-12-05 00:00:00 2022-12-05 11:59:59
            if userid not in user_status:
                user_status[userid] = [(s_t,e_t)]
            else:
                user_status[userid].append((s_t,e_t))
    
    return user_status






